/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author Administrator
 */
public class EmailValidator implements Validator {

    public void validate(FacesContext context, UIComponent component, Object nome) throws ValidatorException {

        if (!(nome instanceof String)) {
            FacesMessage message = new FacesMessage();
            message.setSummary("* Errore irreversibile");
            throw new ValidatorException(message);
        }
        String name = (String) nome;
        //verifico che non sia vuoto
        if (name.length() == 0) {
            FacesMessage message = new FacesMessage();
            message.setSummary("* Devi inserire la tua email");
            throw new ValidatorException(message);
        }
        if (!name.contains(".") && (!(name.contains("@")))) {
            FacesMessage message = new FacesMessage();
            message.setSummary("* L'indirizzo email non è valido");
            throw new ValidatorException(message);
        }
        String regex = "[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(name);

        if (!matcher.matches()) {
            FacesMessage message = new FacesMessage();
            message.setSummary("* Formato indirizzo email non valido");
            throw new ValidatorException(message);
        }
    }
}
